package com.study.chapter05.operator.transform;

import com.study.entity.Event;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @Description:
 * @Author: LiuQun
 * @Date: 2022/7/29 21:51
 */
public class RichFunctionTest {
    public static void main(String[] args) throws Exception {
        //环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<Event> stream = env.fromElements(
                new Event("Mary", "./home", 1000L),
                new Event("Bob", "./cart", 2000L),
                new Event("Alice", "./prod?id=1", 5 * 1000L),
                new Event("Cary", "./home", 60 * 1000L)
        );

        //使用RichMapFunction
        stream.map(new RichMapFunction<Event, Long>() {

            @Override
            public void open(Configuration parameters) throws Exception {
                super.open(parameters);
                System.out.println("索引为"+getRuntimeContext().getIndexOfThisSubtask()+"的任务开始执行");
            }

            @Override
            public Long map(Event event) throws Exception {
                return event.getTimestamp();
            }

            @Override
            public void close() throws Exception {
                super.close();
                System.out.println("索引为"+getRuntimeContext().getIndexOfThisSubtask()+"的任务执行结束");
            }

        }).print();

        env.execute();
    }
}
